﻿using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace General.Mvc.Filters
{
    public class ResponseLogTimeFilter : ActionFilterAttribute
    {
        private const string ResponseTimeKey = "ResponseTimeKey";
        private readonly ILogger logger;

        public ResponseLogTimeFilter(ILogger<ResponseLogTimeFilter> logger)
        {
            this.logger = logger;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // Start the timer   
            context.HttpContext.Items[ResponseTimeKey] = Stopwatch.StartNew();
        }
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Stopwatch stopwatch = (Stopwatch)context.HttpContext.Items[ResponseTimeKey];
            // Calculate the time elapsed   
            var timeElapsed = stopwatch.Elapsed;

            var ip = context.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            }

            logger.LogInformation(new Exception("ip:"+ip.Replace("::ffff:","") +" 请求参数:"+ context.HttpContext.Request.QueryString), context.HttpContext.Request.Method + " " + context.HttpContext.Request.Path + " 耗时:" + timeElapsed.Milliseconds.ToString()+"ms");
        }
    }
}
